/*
 * IGSQLMarcadorDAO.java
 *
 * Created on 8 de noviembre de 2007, 0:07
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package webportlet.model.marcador.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import webportlet.model.marcador.dto.MarcadorDTO;
import webportlet.model.util.DuplicateInstanceException;
import webportlet.model.util.EntityIdentifierGenerator;
import webportlet.model.util.EntityIdentifierGeneratorFactory;
import webportlet.model.util.GeneralOperations;
import webportlet.model.util.InternalErrorException;

/**
 *
 * @author Alvarete
 */
public class IGSQLMarcadorDAO extends AbstractSQLMarcadorDAO{
    
     public MarcadorDTO create(Connection connection, MarcadorDTO marcadorDTO) 
        throws DuplicateInstanceException, InternalErrorException{
        
        PreparedStatement preparedStatement = null;
    
        try {
            /*Get Marcador Identifier. */
            EntityIdentifierGenerator entityIdentifierGenerator =
                    EntityIdentifierGeneratorFactory.getGenerator();
            Long id = entityIdentifierGenerator.nextIdentifier(connection,
                    "Marcador");
            
            /* Create "preparedStatement". */
            String queryString = "INSERT INTO Marcador" +
                " (idMarcador, nombre, url)" +
                " VALUES (?, ?, ?)";
            preparedStatement = connection.prepareStatement(queryString);    
            
            /* Fill "preparedStatement". */
            int i = 1;
            preparedStatement.setLong(i++, id);
            preparedStatement.setString(i++, marcadorDTO.getNombre());
            preparedStatement.setString(i++, marcadorDTO.getUrl());
                        
            /* Execute query. */
            int insertedRows = preparedStatement.executeUpdate();
        
            if (insertedRows == 0) {
                throw new SQLException("Can not add row to table" +
                    " 'Marcador'");
            }

            if (insertedRows > 1) {
                throw new SQLException("Duplicate row for idMarcador = '" + 
                    marcadorDTO.getId() + "' in table 'Marcador'");
            }
            
            return new MarcadorDTO(id,marcadorDTO.getNombre(),
                    marcadorDTO.getUrl());
        
        } catch (SQLException e) {
            throw new InternalErrorException(e);
        } finally {
            GeneralOperations.closeStatement(preparedStatement);
        }  
    }
     
}
